package leetcode.code0385;

public class Solution2 {

	public NestedInteger deserialize(String s) {
		// [[123,[234,345,1234,2234]],[456,[789]]]
		char[] cs = s.toCharArray();
		return (NestedInteger) parse(cs, 0)[0];
	}

	private Object[] parse(char[] cs, int index) {
		// "[1,[2],3,[4]]"
		NestedInteger ans = new NestedInteger();
		NestedInteger ni = null;
		int num = 0;
		int plus = 1;
		for (int i = index; i < cs.length; i++) {
			char c = cs[i];
			if (c == '[') {
				Object[] arr = this.parse(cs, i + 1);
				ni = (NestedInteger) arr[0];
				i = (int) arr[1];
			} else if (c == ']') {
				if (ni == null) {
					ni = new NestedInteger(num * plus);
				}
				return new Object[] { ans, i };
			} else if (c >= '0' && c <= '9') {
				num *= 10;
				num += c - '0';
			} else if (c == '-') {
				plus = -1;
			} else if (c == ',') {
				if (ni == null) {
					ni = new NestedInteger(num * plus);
				}
				ans.add(ni);
				num = 0;
				plus = 1;
				ni = null;
			}
		}
		ni.add(ni);
		return new Object[] { ans };
	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.deserialize("[1,[2],3,[4]]");
		so.deserialize("[123,[456,[789]]]");
		so.deserialize("[[123,[234,345,1234,2234]],[456,[789]]]");
		so.deserialize("[[123,[234,345,1234,2234]],[456,[789]]]");
	}
}
